package com.dd.keel.core.framework.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.dd.keel.core.framework.server.NodeConfig;

/**
 * Service instance factory
 * @author Kevin.XU
 *
 */
public class ServiceInstanceFactory implements  ApplicationContextAware{

	final static private Logger LOGGER = LoggerFactory.getLogger(ServiceInstanceFactory.class);
	
	private NodeConfig nodeConfig;
	
	public NodeConfig getNodeConfig() {
		return nodeConfig;
	}

	public void setNodeConfig(NodeConfig nodeConfig) {
		this.nodeConfig = nodeConfig;
	}	
	
	private ApplicationContext ac;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		ac = applicationContext;
	}

	/**
	 * query service instance
	 * @param group
	 * @param service
	 * @param version
	 * @return
	 */
	public ISoaService getInstance(String group, String service, String version) {
		if(!getNodeConfig().getGroup().equals(group)){
			return null;
		}
		StringBuilder sb = new StringBuilder();
		sb.append(service).append('_').append(version);
		String key = sb.toString();
		ISoaService instance = null;
		try{
			instance = ac.getBean(key, ISoaService.class);
		}catch(BeansException ex){
			LOGGER.error(ex.getMessage(), ex);
		}
		return instance;
	}
	
	/**
	 * query all service names
	 * @return
	 */
	public List<String[]> getAllServices(){
		List<String[]> result = new ArrayList<String[]>();
		try{
			Map<String,ISoaService> serviceMapping = ac.getBeansOfType(ISoaService.class);
			Iterator<String> iter = serviceMapping.keySet().iterator();
			while(iter.hasNext()){
				String name = iter.next();
				String[] array = name.split("_");
				if(array.length==2){
					result.add(new String[]{array[0],array[1]});
				}
			}
		}catch(BeansException ex){
			LOGGER.error(ex.getMessage(), ex);
		}
		return result;
	}
	
}
